/**
 * Created with  SublimeText
 * @Author:      Lyle
 * @DateTime:    2017-06-29 15:50:15
 * @Description: 
 */

import globalMixin from './globalMixin'
import storeDataPartMixin from './storeDataPartMixin'
import chatLib from '../lib/candy/chat'
import * as API from '../api'

var chatPartMixin = {

    mixins: [globalMixin, storeDataPartMixin],

    computed: {

        userInfo() {
            return this.$store.state.user.userInfo;
        },

        errorCode: function() {
            let tthis = this,
                code = this.$store.state.chat.errorCode;
            if (code == 6 || code == 2) {
                this.dialogData = {
                    position: 'middle',
                    type: 'default',
                    content: {
                        info: 'Oops! There was a problem connecting to the chat. Please try again!',
                        btn: [{
                            label: 'Reconnect',
                            btnCallback: function() {
                                tthis.resetChat();
                                if (!ChatObj) {
                                    ChatObj = new chatLib(tthis);
                                }
                            }
                        }]
                    },
                };
            } else if (code === '') {
                this.dialogData = {};
            }
            return code;
        },

    },

    created() {
        let tthis = this;
        this.contented = 0; //0初始 1成功 2连接中
        this.unreadHandler = {
            proccess: function(obj, args) {
                console.log('UnreadHandler', args);
                let callback = function(response) {
                    let obj = {
                        'args': args
                    };
                    //save store， eg unread，userinfo
                    tthis.$store.dispatch('chat_unreadHandler', obj);
                    //if (tthis.loadunreadOK) { tthis.loadunreadOK() }
                }

                if (args.count > 0) {
                    let ids = tthis.handlerUnReadMessagesToIds(args.messages);
                    tthis.getUsersInfo(ids, callback);
                } else {
                    tthis.syncSiteMessageStatus(0);
                }
                /*else {if (tthis.loadunreadOK) { tthis.loadunreadOK() };}*/
            }
        };

        //chatroom & chat & contactListContentMessage
        this.MessageHandler = {
            proccess: function(obj, args) {
                console.log('MessageHandler', obj, args);
                let callback = function(response) {
                    let obj = {
                        'args': args
                    };
                    tthis.$store.dispatch('chat_messageHandler', obj);
                }
                let ids = tthis.handlerMessagesToIds([args]);
                tthis.getUsersInfo(ids, callback);
            }
        };

        this.$root.$on('chat_reset', function() {
            tthis.contented = 0;
        });

        this.$root.$on('chat_connented', function() {
            tthis.contented = 1;
            tthis.connectIM();
        });
    },

    activated() {
        //console.log('activated', this.contented);
        if (this.contented == 0) {
            this.contented = 2;
            this.connectIM();
        }
    },

    methods: {

        onOffline: function() {
            //console.log('onOffline');
            this.dialogData = {
                position: 'middle',
                type: 'default',
                content: {
                    info: 'Oops! There was a problem connecting to the network. Please check network!'
                },
            };
            this.resetChat();
        },

        onOnline: function() {
            //console.log('online');
            this.dialogData = {};
            if (!ChatObj) {
                ChatObj = new chatLib(this);
            }
        },

        syncSiteMessageStatus: function(num) {
            let obj = JSON.parse(Unit.getSessionStorage("siteNumState")) || {};
            if (_.isEmpty(obj)) {
                obj.unread_message_count = {};
            }
            obj.unread_message_count.new_count = num;
            this.$store.dispatch('updateSiteNumStateData', obj);
        },

        resetChat() {
            //store reset 
            this.$store.dispatch('chat_reset');
            //global chatHistory reset 
            ArchiveMessageHistory = {};
            //listen reset
            MiniIM.Handler.reset();
            //notification some component
            this.$root.$emit('chat_reset');
            //reset 
            ChatObj = null;
        },

        connectIM() {
            if (!ChatObj) {
                ChatObj = new chatLib(this);
                console.log('start connectIM');
            } else if (this.contented == 1) {
                if (this.connectOK) { this.connectOK() };
            }
        },

        connectOK() {
            //console.log('component connectOK', this);
            this.$store.dispatch('chat_messageErrorCode', '');
            if (this.componentConnectOK) { this.componentConnectOK() };
        },

        handlerContactMessagesToIds(messages) {
            var users = [];
            for (var i in messages) {
                /*
                let message = messages[i];
                if (message.id !== null && message.id !== 'null') {
                    users.push(message.contactId);
                }
                */
                users.push(i);
            }
            return users;
        },

        handlerUnReadMessagesToIds(messages) {
            var users = [];
            for (var i in messages) {
                /*
                let message = messages[i][0];
                if (message.id !== null && message.id !== 'null') {
                    users.push(message.senderId);
                }
                */
                users.push(i);
            }
            return users;
        },

        handlerMessagesToIds(messages) {
            var users = [];
            for (var i in messages) {
                let message = messages[i];
                if (message.id !== null && message.id !== 'null') {
                    users.push(message.senderId);
                }
            }
            return users;
        },

        filterUsersIdCache(users) {
            var obj = {},
                filterUser = [];
            for (var i in users) {
                if (!this.isCacheHava(users[i]) && _.indexOf(filterUser, users[i]) < 0) {
                    filterUser.push(users[i]);
                }
            }
            return filterUser.join(',');
        },

        isCacheHava: function(id) {
            let bool = false,
                cacheObj = this.getUserObj(id);
            if (!_.isEmpty(cacheObj)) {
                if (cacheObj.im) {
                    bool = true;
                }
            }
            return bool;
        },

        getUsersInfo(userIds, callback) {
            let tthis = this,
                filterUserIds = this.filterUsersIdCache(userIds);
            if (filterUserIds) {
                API.users_profile({
                    data: { ids: filterUserIds },
                    success: function(response) {
                        if (response.result == 1) {
                            tthis.adapterUsersData(response.data);
                            if (callback) {
                                callback(response);
                            }
                        }
                    }
                })
            } else {
                //cached
                if (callback) {
                    callback({});
                }
            }
        },

        adapterUsersData(list) {
            var userListInfo = {};
            for (let i in list) {
                let usr_id = list[i].usr_id,
                    obj = this.mapOneUserData(list[i], i);
                //console.log('adapterUsersData', obj);
                this.setUsersObj(usr_id, obj);
            }
        },

        getAddUsername(username, key) {
            if (typeof(username) != 'undefined') {
                return this.checkRemovedUser(username) ? this.replaceRemovedUser(username) : username
            } else {
                return key
            }
        },

        mapOneUserData(imUserInfo, key) {
            let userInfoObj, userInfoUnit,
                usr_id = imUserInfo.usr_id;

            let cacheObj = this.getUserObj(usr_id);

            if (_.isEmpty(cacheObj)) {
                userInfoUnit = this.userInforStruct();
            } else {
                userInfoUnit = cacheObj;
            }

            userInfoUnit.im = true;
            userInfoObj = userInfoUnit.userInfo;

            //console.log(imUserInfo, imUserInfo.hidden_living_with);
            if (!userInfoUnit.user) {
                //---------------
                userInfoObj.account.age = imUserInfo.age;
                userInfoObj.account.city = imUserInfo.city;
                userInfoObj.account.country_name = imUserInfo.country;
                userInfoObj.account.state_name = imUserInfo.state;
                userInfoObj.status.hidden_living_with = imUserInfo.hidden_living_with;
                userInfoObj.account.gender = imUserInfo.gender;
                userInfoObj.pictures = imUserInfo.picture ? [imUserInfo.picture] : [];
                userInfoObj.status.isGuest = imUserInfo.isGuest;
                userInfoObj.isWinked = imUserInfo.is_winked;
                userInfoObj.status.photo_verify = imUserInfo.photo_verify;
                userInfoObj.account.username = this.getAddUsername(imUserInfo.username_cs, key);
                userInfoObj.account.usr_id = imUserInfo.usr_id;
                userInfoObj.about.headline = imUserInfo.title;
            }
            //---------------
            userInfoObj.status.age_verify = imUserInfo.age_verify;
            userInfoObj.status.can_access_my_private_ablum = imUserInfo.can_access_my_private_ablum;
            userInfoObj.dont_display_preferred = imUserInfo.dont_display_preferred;
            userInfoObj.status.education_verify = imUserInfo.education_verify;
            userInfoObj.hidden_online = imUserInfo.hidden_online;
            userInfoObj.highlight_my_profile = imUserInfo.highlight_my_profile;
            userInfoObj.status.income_verify = imUserInfo.income_verify;
            userInfoObj.status.isBlocked = imUserInfo.is_blocked_by_me;
            userInfoObj.is_chatted = imUserInfo.is_chatted;
            userInfoObj.is_favorite = imUserInfo.is_favorite;
            userInfoObj.is_unavailable = imUserInfo.is_unavailable;
            userInfoObj.membership = imUserInfo.membership;
            userInfoObj.newly_unapproved = imUserInfo.newly_unapproved;
            userInfoObj.numberofpictures = imUserInfo.numberofpictures;
            userInfoObj.status.occupation_verify = imUserInfo.occupation_verify;
            userInfoObj.on_hold = imUserInfo.on_hold;
            userInfoObj.photoCount = imUserInfo.photoCount;
            userInfoObj.profile_hidden = imUserInfo.profile_hidden;

            return userInfoUnit;
        },

        checkRemovedUser: function(username) {
            let patt = new RegExp("^removed_.*");
            return patt.test(username);
        },

        replaceRemovedUser: function(removedUsername) {
            let arr = removedUsername.split('_'),
                len = arr.length,
                usernameArr = (arr.splice(1, len - 3));
            return usernameArr.join("_");
        },

        formatDate(datetime, type) {
            if (!datetime) {
                return;
            }
            var date_msg = new Date(this.correctDateString(datetime));
            var date_now = new Date();
            var monthArr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
            var hours = date_msg.getHours();
            var ampm = hours >= 12 ? ' pm' : ' am';
            hours = hours % 12 || 12;
            if (type == 1) {
                if (date_msg.getFullYear() == date_now.getFullYear() && date_msg.getMonth() == date_now.getMonth() && date_msg.getDate() == date_now.getDate()) {
                    return (hours + ':' + this.formatMinute(date_msg.getMinutes()) + ampm);
                } else if (date_msg.getFullYear() < date_now.getFullYear()) {
                    return ((date_msg.getMonth() + 1) + '/' + date_msg.getDate() + '/' + date_msg.getFullYear());
                } else {
                    return (monthArr[date_msg.getMonth()] + ' ' + date_msg.getDate());
                }
            } else {
                if (date_msg.getFullYear() == date_now.getFullYear() && date_msg.getMonth() == date_now.getMonth() && date_msg.getDate() == date_now.getDate()) {
                    return (hours + ':' + this.formatMinute(date_msg.getMinutes()) + ampm);
                } else if (date_msg.getFullYear() < date_now.getFullYear()) {
                    return (monthArr[date_msg.getMonth()] + ' ' + date_msg.getDate() + ', ' + date_msg.getFullYear() + ' ' + hours + ':' + this.formatMinute(date_msg.getMinutes()) + ampm);
                } else {
                    return (monthArr[date_msg.getMonth()] + ' ' + date_msg.getDate() + ' ' + hours + ':' + (date_msg.getMinutes() < 10 ? ('0' + date_msg.getMinutes()) : date_msg.getMinutes()) + ampm);
                }
            }
        },

        formatMinute(minute) {
            return minute < 10 ? ('0' + minute) : minute;
        },

        correctDateString(datetime) {
            if (!_.isNumber(datetime)) {
                datetime = new Date(datetime).getTime();
            }
            return datetime;
        },

        foreachBlock: function(arr) {
            var newArr = [];
            for (var i in arr) {
                if (arr[i].isBlocked == 0) {
                    newArr.push(arr[i]);
                }
            }
            return newArr;
        },

        isChatroomJid: function(jid) {
            var jid_name = jid.split('@conference.')[0];
            return (jid_name.toLowerCase() == MessageName);
        },

    }

}

export default chatPartMixin;
